const pino = require('pino')
const rfs = require('rotating-file-stream')

const cache = new Map()

function create(path, name) {
    let logger = cache.get(name)
    if (logger) {
        logger.referenceCount++
        return logger.pino
    }
    const stream = rfs.createStream(name, {
        path: path,
        size: '10M',
        interval: '1M',
        compress: 'gzip',
        encoding: 'utf8'
    })
    const self = pino(
        {
            formatters: {
                bindings: bindings => ({ pid: bindings.pid })
            }
        },
        stream
    )
    logger = {
        pino: self,
        stream,
        referenceCount: 1
    }
    cache.set(name, logger)
    return self
}
function toTask(name, logger) {
    let { stream, pino } = logger
    return new Promise(resolve => {
        cache.delete(name)
        pino.flush(() => {
            if (stream.destroyed || stream.closed) {
                resolve()
            } else {
                stream.end(resolve)
            }
        })
    })
}
function close(name) {
    let tasks = []
    if (name) {
        let logger = cache.get(name)
        if (logger) {
            if (logger.referenceCount > 1) {
                logger.referenceCount--
            } else {
                tasks.push(toTask(name, logger))
            }
        }
    } else {
        cache.forEach(logger => {
            tasks.push(toTask(name, logger))
        })
    }
    return Promise.all(tasks)
}

module.exports = {
    create,
    close
}
